<template>
  <view class="wrapper">
    <template v-if="carts.length">
      <!-- 收货信息 -->
      <!-- 看这里... -->
      <view class="shipment">
        <template v-if="address">
          <view class="dt">收货人:</view>
          <view class="dd meta">
            <text class="name">{{ address.userName }}</text>
            <text class="phone">{{ address.telNumber }}</text>
          </view>
          <view class="dt">收货地址:</view>
          <view class="dd">{{ fullAddress }}</view>
        </template>
        <!-- 看这里... -->
        <button v-else style="width: 400rpx" type="primary" block @click="saveAddress">添加收货地址</button>
      </view>

      <!-- 购物车 -->
      <view class="carts">
        <view class="item">
          <!-- 店铺名称 -->
          <view class="shopname">优购生活馆</view>
          <view class="goods" v-for="(item, index) in carts" :key="item.goods_id">
            <!-- 商品图片 -->
            <image class="pic" :src="item.goods_small_logo"></image>
            <!-- 商品信息 -->
            <view class="meta">
              <view class="name">
                {{ item.goods_name }}
              </view>
              <view class="price">
                <text>￥</text>
                {{ item.goods_price }}
                <text>.00</text>
              </view>
              <!-- 加减 -->
              <view class="amount">
                <text class="reduce" @click="decreaseCount(index)">-</text>
                <input type="number" disabled :value="item.goods_number" class="number" />
                <text class="plus" @click="increaseCount(index)">+</text>
              </view>
            </view>
            <!-- 选框 -->
            <view class="checkbox" @click="toggleState(index)">
              <icon type="success" size="20" :color="item.goods_state ? '#ea4451' : '#ccc'"></icon>
            </view>
          </view>
        </view>
      </view>
      <!-- 其它 -->
      <view class="extra">
        <label class="checkall" @click="toggleAll">
          <icon type="success" :color="allChecked ? '#ea4451' : '#ccc'" size="20"></icon>
          全选
        </label>
        <view class="total">
          合计:
          <text>￥</text>
          <label>{{ amount }}</label>
          <text>.00</text>
        </view>
        <view class="pay" @click="goPayment">结算({{ checkdCount }})</view>
      </view>
    </template>
    <view class="tips" v-else>
      <view>空空如也~</view>
      <button type="primary" @click="gotoBuy" style="width: 300rpx; margin-top: 40rpx">去买点啥吧</button>
    </view>
  </view>
</template>

<script>
// 购物车的选中
// 1. 绑定点击事件 点击单选时,需要通过mutation修改选中状态
// 2. 全选,点击的时候也是通过mutation和getters来实现 (点击全选 将vuex中carts每一项中的goods_state修改成跟全选对应的状态)
// 3. 修改商品数量 (通过mutations 修改 goods_number 得需要通过index区分修改谁的)

// 购物车 购买逻辑
// 1. 创建订单
// 	(1) 验证商品是否勾选
//  (2) 验证有没有地址
//  (3) 调接口创建订单
import { mapState, mapGetters } from 'vuex';
import { differenceWith } from 'lodash';
export default {
  data() {
    return {
      order_number: ''
    };
  },
  onLoad() {
    // console.log(this.$store.state.msg);
    // console.log(this.$store.state.m_cart.msg);
    // console.log(this.msg);
    console.log(uni.getStorageSync('carts'));
  },
  computed: {
    // vuex辅助函数的使用 快捷获取state
    ...mapState('m_cart', ['carts']),
    ...mapState('m_user', ['address']),
    ...mapGetters('m_cart', ['allChecked', 'checkdCount', 'amount']),
    ...mapGetters('m_user', ['fullAddress']),
    goods() {
      // 只需要 goods_state为true的商品
      return this.carts.filter((item) => item.goods_state);
    }
  },
  methods: {
    async saveAddress() {
      // #ifndef MP-WEIXIN
      uni.showToast({
        title: '仅在小程序中支持'
      });
      // #endif
      // 同步方式获取收货地址

      // #ifdef MP-WEIXIN
      const { errMsg, ...address } = await uni.chooseAddress();
      console.log(address);
      this.$store.commit('m_user/saveAddress', address);
      // #endif
    },
    // 修改选中状态
    toggleState(index) {
      this.$store.commit('m_cart/toggleState', index);
    },
    // 修改全部选中状态
    toggleAll() {
      this.$store.commit('m_cart/toggleAll', this.allChecked);
    },
    // 数量修改
    decreaseCount(index) {
      this.$store.commit('m_cart/decreaseCount', index);
    },
    increaseCount(index) {
      this.$store.commit('m_cart/increaseCount', index);
    },
    gotoBuy() {
      // 跳转到商品分类页面
      uni.switchTab({
        url: '/pages/category/index'
      });
    },
    async goPayment() {
      await this.createOrder();
      if (!this.order_number) return uni.$showToast('创建订单失败');
      const res = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
        order_number: this.order_number
      });
      console.log(res);
      uni.requestPayment({
        ...res.data.message.pay,
        complete() {
          // 支付成功
          uni.navigateTo({
            url: '/subpkg/pages/order/index'
          });
        }
      });
    },
    async createOrder() {
      // 1. 验证商品是否
      if (this.goods.length === 0) return uni.$showToast('至少选择一个商品');
      // 2 验证地址
      if (!this.fullAddress) return uni.$showToast('请添加收货地址');
      // 调用接口创建订单
      const res = await uni.$http.post('/api/public/v1/my/orders/create', {
        order_price: this.amount,
        consignee_addr: this.fullAddress,
        goods: this.goods
      });
      console.log(res);
      if (res.data.meta.status === 200) this.order_number = res.data.message.order_number;
      // 完善购物车 当生成了订单, 订单里的商品应该从购物车中删除
      const diff = differenceWith(this.carts, this.goods);
      console.log(diff);
      this.$store.commit('m_cart/updateCart', diff);
    }
  }
};
</script>

<style scoped lang="scss">
.shipment {
  height: 100rpx;
  line-height: 2;
  padding: 30rpx 30rpx 40rpx 30rpx;
  font-size: 27rpx;
  color: #333;
  background-color: #fff;
  background-image: url(http://static.botue.com/ugo/images/cart_border%402x.png);
  background-size: contain;
  background-repeat: no-repeat;
  background-position: bottom;

  .dt {
    width: 140rpx;
    float: left;
    clear: both;
  }

  .dd {
    padding-left: 160rpx;
  }

  .meta {
    padding-right: 50rpx;
  }

  text.phone {
    float: right;
  }
}

.carts {
  background-color: #f4f4f4;
  padding-bottom: 110rpx;
  overflow: hidden;

  .shopname {
    padding: 30rpx;
    margin-top: 20rpx;
    font-size: 30rpx;
    color: #333;
    background-color: #fff;
    border-top: 1rpx solid #eee;
    border-bottom: 1rpx solid #eee;
  }

  .goods {
    display: flex;
    padding: 30rpx 20rpx 30rpx 0;
    margin-left: 105rpx;
    border-bottom: 1rpx solid #eee;
    background-color: #fff;

    position: relative;

    .checkbox {
      width: 101rpx;
      height: 100%;
      background-color: #fff;

      display: flex;
      justify-content: center;
      align-items: center;

      position: absolute;
      left: -100rpx;
      top: 0;
    }

    &:last-child {
      border-bottom: none;
    }

    .pic {
      width: 200rpx;
      height: 200rpx;
      margin-right: 30rpx;
    }

    .meta {
      flex: 1;
      font-size: 27rpx;
      color: #333;
      position: relative;
    }

    .name {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .price {
      position: absolute;
      bottom: 0;

      color: #ea4451;
      font-size: 33rpx;

      text {
        font-size: 22rpx;
      }
    }

    .amount {
      position: absolute;
      bottom: 0;
      right: 20rpx;

      height: 48rpx;
      text-align: center;
      border: 1rpx solid #ddd;
      border-radius: 8rpx;

      display: flex;
      align-items: center;

      text {
        display: block;
        width: 60rpx;
        line-height: 48rpx;
        font-size: 36rpx;
        color: #ddd;
        text-align: center;
      }

      input {
        width: 60rpx;
        height: 48rpx;
        min-height: 48rpx;
        font-size: 27rpx;
        border-left: 1rpx solid #ddd;
        border-right: 1rpx solid #ddd;
      }
    }
  }
}

.extra {
  position: fixed;
  bottom: 0;
  /* #ifdef H5 */
  bottom: 50px;
  /* #endif */
  left: 0;
  z-index: 9;

  width: 750rpx;
  height: 96rpx;
  text-align: center;
  line-height: 96rpx;
  font-size: 36rpx;
  border-top: 1rpx solid #eee;
  background-color: #fff;
  color: #333;
  display: flex;

  .checkall {
    width: 140rpx;
    line-height: 1;
    margin-left: 25rpx;
    display: flex;
    align-items: center;

    icon {
      margin-right: 20rpx;
    }
  }

  .total {
    display: flex;
    justify-content: center;
    flex: 1;

    label,
    text {
      color: #ea4451;
      vertical-align: bottom;
      position: relative;
      bottom: -2rpx;
    }

    text {
      position: relative;
      bottom: -3rpx;
      font-size: 24rpx;

      &:first-child {
        margin-left: 10rpx;
      }
    }
  }

  .pay {
    width: 200rpx;
    background-color: #ea4451;
    color: #fff;
  }
}
</style>
